/* ********************************************************************************
 *      Copyright:  (C) 2025 ZYT
 *                  All rights reserved.
 * 
 *       Filename:  socket.c
 *    Description:  This file 
 *                        
 *        Version:  1.0.0(30/03/25)
 *         Author:  Zhang yuting <zhangyuting@163.com>
 *      ChangeLog:  1, Release initial version on "30/03/25 16:37:09"
 *                           
 *********************************************************************************/

#include "client_func.h"


char * get_format_time(time_t current_time)
{
	static char           buf[128];
	struct tm            *tm_info;
	time_t adjusted_time = current_time + 8 * 3600; 

	tm_info = gmtime(&adjusted_time);

	snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d",
			1900 + tm_info->tm_year,   // 年份从1900起算
			1 + tm_info->tm_mon,       // 月份范围0-11，需+1
			tm_info->tm_mday,          // 日期1-31
			tm_info->tm_hour,          // 小时
			tm_info->tm_min, 
			tm_info->tm_sec);

	return buf;
}
int get_time(char *gettime)
{

	if( NULL == gettime )
	{
		log_error("	Invalid input argument\n");
		return -1;
	}

	time_t			sec = 0;
	struct tm		ptm;
	struct tm 		*rv = NULL;

	time(&sec);
	rv = localtime_r(&sec, &ptm);//转换为本地时间

	if( NULL== &ptm )
	{
		log_error("NULL pointer: &resulte\n");
		return -2;

	}

	strftime(gettime, 32, "%Y-%m-%d %H:%M:%S", &ptm);

	log_info("get_time successfully: %s\n", gettime);

	return 0;
}


//Get second from 1970.01.01 00:00:00

void print_usage(char *progname)
{
	printf("%s usage:\n", progname);
	printf("-i(--cli_ip): specfy the cli_ip.\n");
	printf("-p(--cli_port): specfy the cli_port.\n");
	printf("-t(--interval_time): set the interval time(second) of collect temperature.\n");
	printf("-s(--serial_number): set the name of serial number.\n");
	printf("-b(--background): set the program running in the background\n");
	printf("-d(--debug): set LOG_LEVEL_DEBUG and show information in stdress\n");
	printf("-h(--help): print this help information.\n");
	printf("-S(--Stop): Stop background program.\n");

	printf("example: %s -i 127.0.0.1 -p 12345 -t 30 -s RPI_00001\n", progname);

	return ;
}

int set_background_running(int daemon_flag, char *pidfile)
{
	if ( !pidfile )
	{
		return 0;
	}   

	if ( !check_background_running(pidfile) )
	{
		log_warn("Program alread running");
		return 0;
	}

	if ( daemon_flag )      //daemon_flag为1进入后台，0不进入
	{
		daemon(1, 1);
		log_info("Program running as daemon [PID: %d]\n", getpid());
	}

	if (record_daemon_pid(pidfile) < 0)
	{
		log_error("Record PID to \"%s\" failure\n", pidfile);
		return 0;
	}

	return 1;
}


int check_background_running(char *pidfile)
{
	pid_t               pid = -1;
	struct stat         fstatbuf;

	if ( !stat(pidfile, &fstatbuf) )
	{
		log_info("PID record file \"%s\" exist", pidfile);

		pid = get_daemon_pid(pidfile);
		if ( pid > 0 )
		{
			if ( !kill(pid, 0) )    //返回0表示守护进程存在
			{
				log_error("Program with PID[%d] is running\n", pid);
				return 0;
			}

			remove(pidfile);
			return 1;
		}
		if ( 0 == pid )
		{
			log_debug("Read program PID failure\n");    //atoi解析失败
			remove(pidfile);
			return 1;
		}

		log_error("Read record file failure", pidfile);
		return 0;
	}
	return 1;
}

pid_t get_daemon_pid(char *pidfile)
{
	pid_t           pid;
	FILE            *f;
	char            pid_ascii[PID_SIZE];

	f = fopen(pidfile, "rb");
	if ( f != NULL )
	{
		(void)fgets(pid_ascii, PID_SIZE, f);
		(void)fclose(f);
		pid = atoi(pid_ascii);
	}
	else
	{
		log_error("open PID record file failure\n");
		return -1;
	}
	return pid;
}

int record_daemon_pid(char *pidfile)
{
	struct stat         fstatbuf;
	int                 fd = -1;
	int                 mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
	char                ipc_dir[64] = {0};
	char                pid[PID_SIZE];

	strncpy(ipc_dir, pidfile, 64);

	dirname(ipc_dir);

	if ( stat(ipc_dir, &fstatbuf) < 0 )
	{
		if ( mkdir(ipc_dir, mode) < 0 )
		{
			log_error("create \"%s\" failure\n", ipc_dir);
			return -1;
		}

		(void)chmod(ipc_dir, mode);
	}

	mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH;
	fd = open(pidfile, O_RDWR|O_CREAT|O_TRUNC, mode);
	if ( fd < 0 )
	{
		log_error("create \"%s\" failure\n", pidfile);
		return -1;
	}

	snprintf(pid, sizeof(pid), "%u\n", (unsigned)getpid());
	write(fd, pid, strlen(pid));
	close(fd);

	return 0;
}


int stop_background_running(char *pidfile)
{
	pid_t            pid = -1;
	struct stat      fstatbuf;

	if ( stat(pidfile, &fstatbuf) < 0)
	{
		return 0;
	}

	pid = get_daemon_pid(pidfile);
	if (pid > 0)
	{
		while ( (kill(pid, 0) ) == 0 )
		{
			kill(pid, SIGTERM);
			sleep(1);
		}

		remove(pidfile);
	}

	return 0;
}

